package com.only4play.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.only4play.common.model.GeneralResponse;
import com.only4play.common.utils.HttpUtils;
import com.only4play.constant.Oauth2Constant;
import com.only4play.constant.enums.GrantTypeEnum;
import com.only4play.domain.model.RpcAccessToken;
import com.only4play.json.mapper.CustomObjectMapper;

import java.util.HashMap;
import java.util.Map;

/**
 * Oauth2工具类
 *
 * @author liyuncong
 * @date 2023/11/21 10:28
 **/
public class Oauth2Utils {

    private static final ObjectMapper objectMapper = new CustomObjectMapper();

    public static GeneralResponse<RpcAccessToken> getAccessToken(String serverUrl, String appId, String appSecret, String username, String password) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put(Oauth2Constant.GRANT_TYPE, GrantTypeEnum.PASSWORD.getMessage());
        paramMap.put(Oauth2Constant.APP_ID, appId);
        paramMap.put(Oauth2Constant.APP_SECRET, appSecret);
        paramMap.put(Oauth2Constant.LOGIN_USERNAME, username);
        paramMap.put(Oauth2Constant.LOGIN_PASSWORD, password);
        return getHttpAccessToken(serverUrl + Oauth2Constant.ACCESS_TOKEN_URL, paramMap);
    }

    public static GeneralResponse<RpcAccessToken> getAccessToken(String serverUrl, String appId, String appSecret, String code) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put(Oauth2Constant.GRANT_TYPE, GrantTypeEnum.AUTHORIZATION_CODE.getMessage());
        paramMap.put(Oauth2Constant.APP_ID, appId);
        paramMap.put(Oauth2Constant.APP_SECRET, appSecret);
        paramMap.put(Oauth2Constant.AUTH_CODE, code);
        return getHttpAccessToken(serverUrl + Oauth2Constant.ACCESS_TOKEN_URL, paramMap);
    }

    public static GeneralResponse<RpcAccessToken> refreshToken(String serverUrl, String appId, String refreshToken) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put(Oauth2Constant.APP_ID, appId);
        paramMap.put(Oauth2Constant.REFRESH_TOKEN, refreshToken);
        return getHttpAccessToken(serverUrl + Oauth2Constant.REFRESH_TOKEN_URL, paramMap);
    }

    private static GeneralResponse<RpcAccessToken> getHttpAccessToken(String url, Map<String, String> paramMap) {
        String response = HttpUtils.post(url, paramMap);
        try {
            return objectMapper.readValue(response, new TypeReference<>() {
            });
        } catch (Exception exception) {
            return null;
        }
    }
}
